<template>
  <div class="price-setting">
    <a-form-item label="价格设定" name="price_set">
      <a-radio-group v-model:value="_priceSetting" @change="priceSettingChange">
        <a-radio
          :value="item.value"
          v-for="item in PRICE_SETTING"
          :key="item.value"
          class="mr-[61px]"
          :disabled="item.value === 2 || item.value === 3"
          >{{ item.label }}</a-radio
        >
      </a-radio-group>
      <a-form-item-rest>
        <a-form-item class="coin_set" name="price" :rules="goldCoinRules" v-if="goldCoinVisible">
          <a-input v-model:value="_goldCoin" :placeholder="goldCoinPlaceholder" class="gold-coin w-[440px]"> </a-input>
        </a-form-item>
      </a-form-item-rest>
    </a-form-item>
  </div>
</template>

<script lang="ts" setup name="PriceSetting">
import type { Rule } from 'ant-design-vue/es/form'
import type { PriceSettingType, GoldCoinType } from './type'
import { computed, ref, toRefs } from 'vue'
import { PRICE_SETTING } from '@/stores/modules/collect-manage/select-data-source'

// props
type Props = { price_set: PriceSettingType; price: GoldCoinType }
const props = defineProps<Props>()
const { price_set, price } = toRefs(props)

// v-model:newValue
const emit = defineEmits<{
  (e: 'update:price_set', val: PriceSettingType): void
  (e: 'update:price', val: GoldCoinType): void
}>()
const _priceSetting = computed({
  get: () => {
    return price_set.value
  },
  set: (val: PriceSettingType) => {
    emit('update:price_set', val)
  }
})
const _goldCoin = computed({
  get: () => {
    return price.value
  },
  set: (val: GoldCoinType) => {
    console.log('val: ', val)
    emit('update:price', val)
  }
})

let goldCoinVisible = computed(() => price_set.value === 2 || price_set.value === 3)
let goldCoinIsRequired = computed(() => price_set.value === 2 || price_set.value === 3)

let goldCoinPlaceholder = computed(() => {
  switch (price_set.value) {
    case 2:
      return '请输入固定金币数，不填或0为免费'
    case 3:
      return '请输入多个随机金币  使用逗号“,”分隔'
  }
})

let goldCoinValidate = async (_rule: Rule, value: string) => {
  if (price_set.value === 2) {
    if (value) {
      // let reg = /^(0|\+?[1-9][0-9]{0,5})$/
      let reg = /^(0|[1-9][0-9]{0,5})$/
      if (!reg.test(value)) return Promise.reject('请输入0-999999的整数')
    }
  }

  if (price_set.value === 3) {
    if (!value) {
      return Promise.reject(goldCoinPlaceholder.value)
    } else {
      let reg = /^(0|[1-9][0-9]{0,5})(,(0|[1-9][0-9]{0,5}))*$/
      if (!reg.test(value)) return Promise.reject('请输入0-999999的整数，多个金币使用英文逗号分隔')
    }
  }

  return Promise.resolve()
}

const goldCoinRules = [{ validator: goldCoinValidate, trigger: 'blur' }]

const priceSettingChange = () => {
  _goldCoin.value = ''
}
</script>

<style lang="less" scoped>
.price-setting {
  .coin_set {
    margin-top: 10px;
    margin-bottom: 0;
  }
}
</style>
